package com.example.demo.component.docker;

import com.example.demo.component.osql.osql_client;
import com.spotify.docker.client.messages.Container;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName docker_client_util
 * @Description
 * @date 2023/1/28 16:28
 * @Author yanceysong
 * @Version 1.0
 */
public class docker_client_util {
    /**
     * 获取sha256信息
     *
     * @param image_name 镜像名称
     * @param tag        版本号
     * @return 结果
     */
    protected static String get_digest(String image_name, String tag) {
        String sha256_url = "http://" + docker_client.DOCKER_REPOSITORY_ADDRESS + ":5000/v2/" + image_name + "/manifests/" + tag;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(sha256_url);
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            httpGet.addHeader("Accept", "application/vnd.docker.distribution.manifest.v2+json");
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                Header[] allHeaders = response.getAllHeaders();
                for (Header h : allHeaders) {
                    if (h.getName().equals("Docker-Content-Digest"))
                        return h.getValue();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tag;
    }

    /**
     * 执行命令方法
     *
     * @param commands 指令的集合
     * @return 执行的结果
     */
    protected static String execute(ArrayList<String> commands) {
        StringBuilder sb = new StringBuilder();
        Runtime run = Runtime.getRuntime();
        Process proc = null;
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            proc = run.exec(System.getProperty("os.name").toLowerCase().contains("windows") ? osql_client.CMD_PATH : "/bin/bash", null);
            if (proc != null) {
                in = new BufferedReader(new InputStreamReader(proc.getInputStream(), (String) System.getProperties().get("sun.jnu.encoding")));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
                commands.forEach(out::println);
                out.println("exit");
                String line;
                int now = 0;
                while ((line = in.readLine()) != null) {
                    now++;
                    if (now == 5) {
                        sb.append(line);
                        break;
                    }
                }
                proc.waitFor();
                in.close();
                out.close();
                proc.destroy();
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (proc != null) proc.destroy();
                if (in != null) in.close();
                if (out != null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString().equals("") ? "{}" : sb.toString();
    }

    public static void main(String[] args) {
//        boolean ap = docker_client.delete_repository_image("ap", "v0.7");
//        System.out.println(ap);
        docker_client client = docker_client_factory.get_docker_client("192.168.75.132");
        List<Container> all_containers = client.get_all_containers();
        for(Container c:all_containers){
            if (Objects.requireNonNull(c.names()).get(0).contains("registry")){
               if (Objects.equals(c.state(), "running"));
//                client.kill_container(c.id());
//                client.remove_container(c.id());
            }
        }
        client.close();
        System.out.println(all_containers);
    }

}
